const HtmlWebpackPlugin = require("html-webpack-plugin");
const fs = require('fs');

module.exports = class HtmlWebpackPluginIgnore {
  apply(compiler) {
    compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
      console.log("html-webpack-plugin-ignore is starting");
      HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapAsync(
        "html-webpack-plugin-ignore",
        (data, cb) => {
          try {
            const templatePath = data.plugin.options.template;
            const templateData = fs.readFileSync(templatePath, {
              encoding: "utf-8",
            });
            // 源文件中的 html
            const sourceHtml = templateData.match(
              /(<!-- html-webpack-plugin-ignore-start -->[\s\S]*?<!-- html-webpack-plugin-ignore-end -->)/g
            );

            let index = 0;
            let resultHtml = data.html.replace(
              /(<!-- html-webpack-plugin-ignore-start -->[\s\S]*?<!-- html-webpack-plugin-ignore-end -->)/g,
              () => {
                return sourceHtml[index++];
              }
            );
            data.html = resultHtml;
          } catch (err) {
            console.log("html-webpack-plugin-ignore:fail", JSON.stringify(err));
          }

          cb(null, data);
        }
      );
    });
  }
};
